package com.example.petproject.service.impl;

import com.example.petproject.entity.dto.CommentListDTO;
import com.example.petproject.entity.dto.PostCommentDTO;
import com.example.petproject.entity.model.PmsComment;
import com.example.petproject.entity.model.PmsCommentPic;
import com.example.petproject.entity.model.UmsUser;
import com.example.petproject.entity.vo.CommentListVO;
import com.example.petproject.entity.vo.PageResult;
import com.example.petproject.entity.vo.ReturnStatusEnum;
import com.example.petproject.execption.BaseException;
import com.example.petproject.mapper.PmsCommentMapper;
import com.example.petproject.mapper.PmsCommentPicMapper;
import com.example.petproject.service.PmsCommentService;
import com.example.petproject.service.third.ali.AliYunOSSService;
import com.example.petproject.util.ObjectMapperUtils;
import com.example.petproject.util.PetUmsUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.security.auth.login.LoginContext;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 包名称：com.example.petproject.service.impl
 * 类名称：PmsCommentServiceImpl
 * 类描述：评价列表实现
 * 创建人：@author DrinkMore-HotWater
 * 创建时间：2024年01月10日 10:57
 **/
@Service
public class PmsCommentServiceImpl implements PmsCommentService {
    private static final Logger log = LoggerFactory.getLogger(PmsCommentServiceImpl.class);
    @Resource
    private PmsCommentMapper pmsCommentMapper;
    @Resource
    private PmsCommentPicMapper pmsCommentPicMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private AliYunOSSService aliYunOSSService;


    /**
     * 获取评价列表
     *
     * @param commentListDTO 条件类
     * @return PageResult<List < CommentListVO>>
     */
    @Override
    public PageResult<CommentListVO> getCommentList(CommentListDTO commentListDTO) {
        PageHelper.startPage(commentListDTO.getPageNo(), 10);
        Page<CommentListVO> page = pmsCommentMapper.selectComment(commentListDTO);
        page.forEach(commentVO ->{
            List<String> picUrlList = pmsCommentPicMapper.selectPicUrlByCommentId(commentVO.getCommentId());
            if (!CollectionUtils.isEmpty(picUrlList)) {
                List<String> imgList = picUrlList.stream().map(picUrl -> aliYunOSSService.getSymink(picUrl)).toList();
                commentVO.setImgList(imgList);
            }
        });
        return PageResult.ok(page);
    }

    @Override
    public void postComment(String token, PostCommentDTO postCommentDTO) {
        UmsUser umsUser = null;
        try {
            //判断token是否为空
            if (ObjectUtils.isEmpty(token)) {
                throw new BaseException(ReturnStatusEnum.AUTH_TOKEN_EMPTY);
            }
            //从redis中取出token
            String redisToken = PetUmsUtils.generateTokenRedisKey(token);
            String userStr = stringRedisTemplate.opsForValue().get(redisToken);
            if (ObjectUtils.isEmpty(userStr)) {
                throw new BaseException(ReturnStatusEnum.AUTH_USER_NOT_LOGIN);
            }
            //将取出的用户信息序列化
            umsUser = ObjectMapperUtils.stringToObj(userStr, UmsUser.class);
            PmsComment pmsComment = new PmsComment();

            List<Long> imgIds = postCommentDTO.getImgIds();
            //判断图片是否为空
            BeanUtils.copyProperties(postCommentDTO, pmsComment);
            int isPic = CollectionUtils.isEmpty(imgIds) ? 0 : 1;
            pmsComment.setIsPic(isPic);
            pmsComment.setUserId(umsUser.getId());
            pmsComment.setCreatedTime(LocalDateTime.now());
            pmsComment.setUpdatedTime(LocalDateTime.now());
            //插入评论
            int result = pmsCommentMapper.insertSelective(pmsComment);
            if (result>0) {
                //更新图片，先根据图片id查询出对应的图片
                if (!CollectionUtils.isEmpty(imgIds)) {
                    imgIds.forEach(imgId -> {
                        PmsCommentPic pmsCommentPic = pmsCommentPicMapper.selectByPrimaryKey(imgId);
                        if (!ObjectUtils.isEmpty(pmsCommentPic)) {
                            pmsCommentPic.setCommentId(pmsComment.getId());
                            pmsCommentPic.setUpdatedTime(LocalDateTime.now());
                            pmsCommentPicMapper.updateByPrimaryKeySelective(pmsCommentPic);
                        }
                    });
                }
            }

            log.info("pmsComment:{}", pmsComment);
        } catch (JsonProcessingException e) {
            log.error("用户信息反序列化失败：", e);
            throw new BaseException(ReturnStatusEnum.SYSTEM_EXCEPTION);
        }
    }
}
